// 页面加载时，从缓存中获取购物车数据渲染到页面中
// 要求是checked = true
import { getSetting,chooseAddress,openSetting, showModal, showToast, requestPayment } from '../../utils/asyncWx.js';
import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from '../../request/index'

Page({
  data: {
    address:{},
    cart:[],
    totalPrice: 0,
    totalNum: 0,
    showPop: false,
    animationData: {},
    checked: true,
    remark: null
  },
  onShow(){
    wx.showLoading({
      title: '加载中',
    })
    //获取缓存中的收货地址信息
    const address = wx.getStorageSync("address");
    //获取缓存中购物车数据
    let cart = wx.getStorageSync("cart") || [];
    // 过滤购物车数组
    cart = cart.filter(v => v.checked)
    this.setData({
      address
    });
    //总价格 总数量
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
        totalPrice += v.num * v.market_price;
        totalNum += v.num; 
    });
    //给 data赋值
    this.setData({
      cart,
      address,
      totalNum,
      totalPrice
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 1500)
  },
  // 跳转到授权页面获取token
  async handleOrderPay() {
    try {
        // 1.判断有没有token
      const token = wx.getStorageSync("token");
      // 2.判断
      if(!token) {
        wx.navigateTo({
          url: '/pages/auth/auth'
        });
        return;
      }
      // 3.创建订单
      // 3.1获取请求头参数
      const header = { Authorization: token };
      // 3.2获取请求体参数
      const order_price = this.data.totalPrice;
      const consignee_addr = this.data.address.all;
      const cart = this.data.cart;
      // 3.3获取goods
      let goods = [];
      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.market_price
      }))
      const orderParams = { order_price, consignee_addr, goods };
      // 4.准备发送请求，创建订单编号
      const {order_number} = await request({
        url: '/my/orders/create',
        method: 'post',
        data:orderParams,
        header
      })
      // 5.准备预支付
      const {pay} = await request({
        url: '/my/orders/req_unifiedorder',
        method: 'post',
        data: {order_number},
        header
      })
      // 6.发起微信支付
      await requestPayment(pay);
      // 7.查询后台订单状态
      const res = await request({
        url: '/my/orders/chkOrder',
        method: 'post',
        data: {order_number},
        header
      })
      await showToast({
        title: '支付成功'
      })
      // 8.手动删除缓存中已经支付了的商品
      let newCart = wx.getStorageSync('cart');
      newCart = newCart.filter(v => !v.checked);
      wx.setStorageSync('cart', newCart);
      
      // 9.支付成功跳转到订单页面
      wx.navigateTo({
        url: '/pages/order/order'
      });
    } catch (error) {
      console.log(error);
      await showToast({
        title: '支付失败'
      })
    }
  },
  // 显示底部弹层
  showModal: function() {
    var _this = this;
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
      delay: 0
    })
    _this.animation = animation
    animation.translateY(300).step()
    _this.setData({
      animationData: animation.export(),
      showPop: true
    })
    setTimeout(function() {
      animation.translateY(0).step()
      _this.setData({
        animationData: animation.export()
      })
    }.bind(_this), 50)
  },
  // 隐藏底部弹层
  hideModal: function() {
    var _this = this;
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: "ease",
      delay: 0
    })
    _this.animation = animation
    animation.translateY(300).step()
    _this.setData({
      animationData: animation.export(),
    })
    setTimeout(function() {
      animation.translateY(0).step()
      _this.setData({
        animationData: animation.export(),
        showPop: false
      })
    }.bind(this), 200)
  },
  changeRadio() {
    let { checked } = this.data
    checked = !checked
    this.setData({
      checked
    })
  },
  getRemark(e) {
    this.setData({
      remark: e.detail.value
    })
  }
}) 